package com.qf.Filter;

import com.alibaba.fastjson.JSON;
import com.qf.pojo.Result;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
//控制这个过滤器的执行优先级,值越小,优先级越高
@Order(-5)
public class MyLoginFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求参数中是否有token(实际开发应该是获取jwt串)
        ServerHttpRequest request = exchange.getRequest();
        //获取请求参数中,指定键对应的值
        String token = request.getQueryParams().getFirst("token");

        if (token == null || token.length()==0){
            //没有token信息
            Result result = Result.error("请先登录");
            String json = JSON.toJSONString(result);

            //解决中文响应乱码问题
            exchange.getResponse().getHeaders().add("content-type","text/html;charset=utf-8");

            //将以上信息响应到页面
            DataBuffer dataBuffer = exchange.getResponse().bufferFactory().wrap(json.getBytes(StandardCharsets.UTF_8));
            //这个Mono对象就是我们writeWith需要的publisher对象
            Mono<DataBuffer> mono = Mono.just(dataBuffer);
            return exchange.getResponse().writeWith(mono);
        }

        //有token,放行
        return chain.filter(exchange);
    }
}
